package com.wn.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wn.bean.*;
import com.wn.service.IOwnerService;
import com.wn.service.IParkingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.jws.Oneway;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yellow Docter
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/parking")
public class ParkingController {

    @Autowired
    private IParkingService parkingService;

    @Autowired
    private IOwnerService iOwnerService;

    @GetMapping
    public R queryHouse(Integer currentPage,Integer pageSize,String numbers){

        IPage<Parking> page = new Page<>(currentPage,pageSize);

        //条件查询
        QueryWrapper<Parking> qr = new QueryWrapper<>();

        if (StringUtils.hasLength(numbers)){
            qr.eq("numbers",numbers);
        }

        IPage<Parking> parkingIPage = parkingService.page(page,qr);

        List<Parking> records = parkingIPage.getRecords();

        records.forEach(park->{
            Owner owner = iOwnerService.getById(park.getOwnerId());
            park.setOwner(owner);
        });

        Long total = parkingIPage.getTotal();

        // 组装数据返回结果
        R r = new R();

        if (!CollectionUtils.isEmpty(records)){
            PageBean<Parking> pageBean = new PageBean<>();
            pageBean.setData(records);
            pageBean.setTotal(total.intValue());

            r.setData(pageBean);
            r.setMsg("查询成功");
            r.setCode(Constants.SUCCESS_CODE);

            return r;
        }
        return R.ERROR("查询失败");
    }

    @PostMapping
    public R addPark(@RequestBody Parking parking){

        parking.setStatus(0);
        boolean save = parkingService.save(parking);

        if (save){
            return R.OK("添加成功...");
        }
        return R.ERROR();
    }

    @PutMapping
    public R updatePark(@RequestBody Parking parking){

        boolean save = parkingService.updateById(parking);

        if (save){
            return R.OK("修改成功...");
        }
        return R.ERROR();
    }


}
